package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    public StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2. 如果不符合，返回错误信息
            return Result.fail("手机格式错误");
        }
        // 3. 符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 4. 保存验证码到redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 5. 发送验证码
        log.debug("发送短信验证码成功，验证码是{}",code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();
        String code = loginForm.getCode();
        // 1. 校验手机号
        if (phone==null||RegexUtils.isPhoneInvalid(phone))
        {
            // 2. 如果不符合，返回错误信息
            return Result.fail("手机号不合法");
        }

        // TODO 3. 从redis获取验证码并校验
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (cacheCode==null||!cacheCode.equals(code)){
            //不一致则报错
            return  Result.fail("验证码错误");
        }
        // 4. 查询用户是否存在
        User user = query().eq("phone", loginForm.getPhone()).one();
        // 没有则创建用户
        if (user==null){
            // 5. 不存在则创立用户并存储到数据库之中
            user=createUser(loginForm.getPhone());
        }
        //TODO 6. 保存用户信息到redis中
        //6.1 随机生成token作为登录令牌
        String token = UUID.randomUUID().toString(true);
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;

        //TODO 6.2 将user对象转化为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create()
                .ignoreNullValue().setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString())
        );

        //TODO 6.3 存储
        stringRedisTemplate.opsForHash().putAll(tokenKey,map);
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);
        //TODO 7. 返回token回客户端
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 获取日期
        LocalDateTime localDateTime = LocalDateTime.now();
        // 3. 拼接key
        String keySuffix = localDateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        // 4. 获取今天是本月的第几天
        int day = localDateTime.getDayOfMonth();
        // 5. 写入redis
        stringRedisTemplate.opsForValue().setBit(key,day-1,true);
        // 6. 返回成功
        return Result.ok(true);
    }

    @Override
    public Result signCount() {
        // 获取本月截至今天的所有签到记录，返回一个十进制的数字
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 获取日期
        LocalDateTime localDateTime = LocalDateTime.now();
        // 3. 拼接key
        int month=localDateTime.getMonthValue();
        int day=localDateTime.getDayOfMonth();
        int year=localDateTime.getYear();
        String keySuffix = localDateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        List<Long> resultNum = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType
                .unsigned(day - 1)).valueAt(0));
        if (resultNum==null||resultNum.size()==0){
            return Result.ok();
        }
        int cnt=0;
        Long result=resultNum.get(0);
        while (result!=0){
            if ((result&1)==0L){
                break;
            }
            cnt++;
            result>>>=1;
        }
        return Result.ok(cnt);

    }

    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        this.save(user);
        return user;
    }


}
